package com.zline.foodraise.ui.activity;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.TemplateChooseAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.TemplateBean;
import com.zline.foodraise.entity.TradingBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.MyGridLayoutManager;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by heshantao on 15/8/30.
 * 模板选择
 */
@EActivity(R.layout.activity_template_choose)
public class TemplateChooseActivity extends ZlineActivity implements RecyclerItemClicked {
    private static final String LOG_TAG = TemplateChooseActivity.class.getSimpleName();
    //标题
    @StringRes(R.string.template_chooser)
    String title;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    @ViewById(R.id.template_choose_srl)
    SwipeRefreshLayout swipeRefreshLayout;
    @ViewById(R.id.template_choose_rv)
    RecyclerView template_rv;
    @Bean
    TemplateChooseAdapter adapter;
    @Extra
    long projectId;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    int curPage = 1;
    @Bean
    HttpDataParsing httpDataParsing;
    SparseArray<TemplateBean> templateBeanSparseArray = new SparseArray<TemplateBean>();
    ArrayList<TemplateBean> templateBeanList;
    @Bean
    NetworkUtil networkUtil;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @ViewById(R.id.ex_no_data_rl)
    RelativeLayout no_data_rl;
    //是否加载失败
    boolean loadFail = false;
    //第一次加载数据
    boolean firstLoad = true;
    //加载更多
    boolean loadMore = false;


    @AfterViews
    void doSomeAfterView() {
        initView();
        requestTemplateData();
    }

    void initView() {
        title_tv.setText(title);
        initSwipRefreshLayout();
        initTemplateRecyclerView();
    }


    //网络请求模板信息
    void requestTemplateData() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            requestTemplateList(curPage);
        } else {
            showLoadFailView(true);
            TUtil.showShort(this, R.string.no_network);
        }
    }

    //是否加载失败显示重新加载页面
    void showLoadFailView(boolean isException) {
        loadFail = isException;
        if (isException) {
            exception_rl.setVisibility(View.VISIBLE);
        } else {
            exception_rl.setVisibility(View.GONE);
        }
    }

    //是否显示暂无数据
    void showNoDataView(boolean noData) {
        if (noData) {
            no_data_rl.setVisibility(View.VISIBLE);
        } else {
            no_data_rl.setVisibility(View.GONE);
        }
    }

    //请求获得模板信息
    void requestTemplateList(int currentPage) {
        httpOperator.requestTemplateList(httpUtil, projectId, Constant.PAGE_ROWS_NUMBER, currentPage, requestTemplateListHandler);
    }

    //请求模板信息回调
    AsyncHttpResponseHandler requestTemplateListHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestTemplateListHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        templateBeanSparseArray = httpDataParsing.getTemplateInfo(response);
                        sparseArrayTransformList(templateBeanSparseArray);
                        if (swipeRefreshLayout.isRefreshing()) {
                            refreshData(templateBeanSparseArray);
                        } else {
                            loadMoreData(templateBeanSparseArray);
                        }

                    } else {
                        loadFailInfo();
                        if (firstLoad) {
                            showLoadFailView(true);
                        } else {
                            httpErro.showCommonErroResult(resultCode);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    firstLoad = false;
                    dissLoadingDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            loadFailInfo();
            dissLoadingDialog();
            if (firstLoad) {
                showLoadFailView(true);
            }
        }
    };

    void sparseArrayTransformList(SparseArray<TemplateBean> array) {
        templateBeanList = new ArrayList<TemplateBean>();
        for (int m = 0; m < array.size(); m++) {
            templateBeanList.add(array.get(m));
        }
    }


    //设置recyclerView
    void initTemplateRecyclerView() {
        template_rv.setItemAnimator(new DefaultItemAnimator());//设置动画
        MyGridLayoutManager layoutManager = new MyGridLayoutManager(this, 2);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        template_rv.setLayoutManager(layoutManager);
        adapter.setAdapterData(templateBeanSparseArray);
        adapter.setRecycleItemClickListener(this);
        template_rv.setAdapter(adapter);
    }

    //初始化SwipRefreshLayout
    void initSwipRefreshLayout() {
        //设置加载颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (networkUtil.isNetworkAvailable()) {
                    requestTemplateList(curPage);
                } else {
                    stopRefresh();
                    TUtil.showShort(TemplateChooseActivity.this, R.string.no_network);
                }

            }
        });
    }


    //刷新数据
    void refreshData(SparseArray<TemplateBean> templateArray) {
        if (loadFail) {
            showLoadFailView(false);
        }
        adapter.setAdapterData(templateArray);
        adapter.notifyDataSetChanged();
        stopRefresh();
        isNoDataException();
    }

    //加载更多数据
    void loadMoreData(SparseArray<TemplateBean> templateArray) {
        loadMore = false;
        if (loadFail) {
            showLoadFailView(false);
        }
        adapter.addAll(templateArray);
        if (curPage == 1) {
            isNoDataException();
        }
    }

    //是否显示暂时没有数据
    void isNoDataException() {
        int size = adapter.getArrys().size();
        if (size == 0) {
            showNoDataView(true);
        } else {
            showNoDataView(false);
        }
    }


    //加载失败时候情况处理
    void loadFailInfo() {
        stopRefresh();
        firstLoad = false;
    }


    //停止刷新
    void stopRefresh() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    @Override
    public void onRecyclerItemClicked(int position) {
        PhotoSelectWithTemplateActivity_.intent(this).mPosition(position).templateArry(templateBeanList).start();
    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {

    }

    @Override
    public void onRecyclerClickedDelete(int position) {

    }

    @Click({R.id.app_common_header_left_icon_iv, R.id.reload_tv})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.reload_tv:
                requestTemplateData();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
        StatService.onPageStart(this, Constant.TEMPLATE_CHOOSE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
        StatService.onPageEnd(this, Constant.TEMPLATE_CHOOSE);
    }
}
